package com.app.controller;

import com.app.model.JiuquanUserModel;
import com.app.model.ModuleCountModel;
import com.app.model.UserCountModel;
import com.app.service.ModuleCountService;
import com.app.service.UserCountService;
import com.app.service.UserService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

//酒泉用户统计
@RestController
@Controller
@RequestMapping("/jiuquan/userCount")
public class UserCountController {
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleCountService moduleCountService;

    //新增访问
    @PostMapping("/addUserCount")
    public Result addUserCount(HttpServletRequest request) {
        UserCountModel userCountModel = new UserCountModel();
        userCountModel.setCreateTime(CommonHelp.getNowTimestamp());
        String token = request.getHeader("token");
        if (token == null) {
            userCountService.save(userCountModel);
            return Result.success("访问成功");
        }
        String openId = TokenUtils.verify(token);
        JiuquanUserModel userInfo = userService.getUserByOpenid(openId);
        userCountModel.setUserId(userInfo.getId());
        userCountService.save(userCountModel);
        return Result.success("访问成功");
    }

    //各功能模块访问数量+1
    @GetMapping("/addModuleCount")
    public Result<Object> addModuleCount(Integer type) {
        QueryWrapper<ModuleCountModel> qw = new QueryWrapper<>();
        qw.eq("type", type);
        ModuleCountModel moduleCount = moduleCountService.getOne(qw);
        Integer count = moduleCount.getCount();
        count = count + 1;
        moduleCount.setCount(count);
        UpdateWrapper<ModuleCountModel> uw = new UpdateWrapper<>();
        uw.eq("type",type);
        moduleCountService.update(moduleCount,uw);
        System.out.println(type);
        return Result.success(moduleCount.getName()+"访问+1");
    }


}
